package guestbook;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TikServlet extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        // We have one entity group per tiktolk with all contentkings residing
        // in the same entity group as the contenttolk to which they belong.
        // This lets us run a transactional ancestor query to retrieve all
        // contentkings for a given contenttolk.  However, the write rate to each
        // contenttolk should be limited to ~1/second.
        String tiktolkName = req.getParameter("tiktolkName");
        Key tiktolkKey = KeyFactory.createKey("tiktolk", tiktolkName);
        String content = req.getParameter("content");
        Date date = new Date();
        Entity tikking = new Entity("tikking", tiktolkKey);
        tikking.setProperty("user", user);
        tikking.setProperty("date", date);
        tikking.setProperty("content", content);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(tikking);

        resp.sendRedirect("/tik.jsp?tiktolkName=" + tiktolkName);
    }
}

